package config

import (
	"errors"
	"fmt"
	"github.com/spf13/viper"
	"os"
	"path/filepath"
	"strings"
)

type Config struct {
	// 消息队列
	RdsHost     string // redis 主机
	RdsPort     int
	RdsPassword string
	RdsDb       int
	Rountines   int
	Cycles      int
}

func Init(file string) (*Config, error) {
	_, err := os.Stat(file)
	if err == nil {
		return LoadFromFile(file)
	}
	return nil, err
}

func parseConfigPath(confFile string) (string, string, string, error) {
	confDir := filepath.Dir(confFile)
	confBase := filepath.Base(confFile)
	nameType := strings.Split(confBase, ".")
	if len(nameType) != 2 {
		return "", "", "", errors.New(fmt.Sprintf("confBase has no suffix type. confBase: [%v]", confBase))
	}
	confName := nameType[0]
	confType := nameType[1]

	return confDir, confName, confType, nil
}

func LoadFromFile(file string) (*Config, error) {
	viperCfg := viper.New()
	confDir, confBase, confType, err := parseConfigPath(file)
	if err != nil {
		return nil, err
	}
	viperCfg.AddConfigPath(confDir)
	viperCfg.SetConfigName(confBase)
	viperCfg.SetConfigType(confType)
	if err := viperCfg.ReadInConfig(); err != nil {
		return nil, err
	}

	cfg := &Config{}
	cfg.RdsHost = viperCfg.GetString("redis.host")
	cfg.RdsPort = viperCfg.GetInt("redis.port")
	cfg.RdsPassword = viperCfg.GetString("redis.password")
	cfg.RdsDb = viperCfg.GetInt("redis.db")
	cfg.Rountines = viperCfg.GetInt("routines")
	cfg.Cycles = viperCfg.GetInt("cycles")
	return cfg, nil
}
